package edu.nf.project.webs.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.project.services.response.ResultVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(urlPatterns = "/*")
public class AuthFilter implements Filter {

    private static List<String> list;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        list = Arrays.asList("/api/users/login");
        System.out.println("过滤器初始化成功");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 打印所有请求头
        System.out.println("=== 请求头信息 ===");
        java.util.Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println(headerName + ": " + request.getHeader(headerName));
        }
        System.out.println("=== 请求头信息结束 ===");

        // 处理 OPTIONS 请求
        if ("OPTIONS".equals(request.getMethod())) {
            System.out.println("处理 OPTIONS 请求");
            response.setStatus(HttpServletResponse.SC_OK);
            // 添加CORS响应头
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With, auth");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Max-Age", "3600");
            return;
        }

        //判断请求地址，如果是认证和登陆页面则直接放行
        String url = request.getRequestURI();
        System.out.println("当前请求URL: " + url);

        // 如果是 /api/messages 开头的路径，直接放行
        if (url.startsWith("/api/messages")) {
            System.out.println("URL以 /api/messages 开头，直接放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if(list.contains(url)) {
            System.out.println("URL在放行列表中，直接放行");
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //获取token认证
            String token = request.getHeader("auth");
            System.out.println("auth token: " + token);

            if(token != null && !token.isEmpty() && !token.equals("null")) {
                System.out.println("token有效，放行请求");
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                //先判断是否是ajax请求，如果是则响应ResultVO
                //否则重定向到登陆页面
                String requestType = request.getHeader("X-Requested-With");
                System.out.println("X-Requested-With: " + requestType);

                if("XMLHttpRequest".equals(requestType)) {
                    System.out.println("是AJAX请求，返回JSON响应");
                    //响应vo
                    ResultVO<String> vo = new ResultVO<>();
                    vo.setCode(HttpStatus.UNAUTHORIZED.value());
                    vo.setMessage("尚未登录");
                    response.setContentType("application/json");
                    //将vo转换成json字符串
                    String json = new ObjectMapper().writeValueAsString(vo);
                    response.getWriter().write(json);
                } else {
                    System.out.println("不是AJAX请求");
                }
            }
        }
    }
}